package com.bears.god.sup.servlet.operation;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bears.god.sup.model.Dept;
import com.bears.god.sup.service.IdeptService;
import com.bears.god.sup.service.ServiceDAOFactory;

@WebServlet("/addDept.do")
public class AddDeptServlet extends HttpServlet {

	private static final long serialVersionUID = 123456L;

	public static final String METHOD_ADD = "0";
	public static final String METHOD_FINISH = "1";

	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setCharacterEncoding("UTF-8");
		req.setCharacterEncoding("UTF-8");
		String method = req.getParameter("method");

		if (method != null) {
			switch (method) {
			case AddDeptServlet.METHOD_ADD:
				add(req, resp);
				break;
			case AddDeptServlet.METHOD_FINISH:
				finish(req, resp);
				break;

			default:
				break;
			}
		}
	}

	private void add(HttpServletRequest req, HttpServletResponse resp) {
		try {

			req.getRequestDispatcher("WEB-INF/view/manager/addDept.jsp").forward(req, resp);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void finish(HttpServletRequest req, HttpServletResponse resp) {
		Dept dept = new Dept();

		try {
			String deptName = req.getParameter("deptName");
			String description = req.getParameter("description");
			dept.setDepartmentName(deptName);
			dept.setDescription(description);

			IdeptService deptService = ServiceDAOFactory.getDeptDAO();
			deptService.save(dept);

			req.setAttribute("addDept_success", "添加成功");
			req.getRequestDispatcher("/deptlist").forward(req, resp);
		} catch (Exception e) {
			e.printStackTrace();
			try {
				req.setAttribute("addDept_err", "添加失败");
				req.getRequestDispatcher("WEB-INF/view/manager/addDept.jsp").forward(req, resp);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
	}

}
